//https://leetcode.cn/problems/combination-sum-ii/
package codeRandomThoughts.Test40组合总和II;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Solution {
    List<Integer> path = new ArrayList<>();
    List<List<Integer>> result = new ArrayList<>();
    int sum = 0;

    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        int startIndex = 0;
        Arrays.sort(candidates);
        backtracking(candidates, target, startIndex);
        return result;
    }

    public void backtracking(int[] candidates, int target, int startIndex) {
        //终止条件
        if (sum == target) {
            result.add(new ArrayList<>(path));
            return;
        } else if (sum > target) {
            return;
        }
        int[] empty = new int[55];

        //横向搜索
        for (int i = startIndex; i < candidates.length; i++) {
            if (sum+candidates[i]>target){
                return;
            }
            if (empty[candidates[i]]==0){
                sum += candidates[i];
                path.add(candidates[i]);
                empty[candidates[i]]=1;
                backtracking(candidates, target, i + 1);
                sum -= candidates[i];
                path.remove(path.size() - 1);
            }
        }
    }

}
